package com.goodlearning.gloriamobile.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.goodlearning.gloriamobile.R;
import com.goodlearning.gloriamobile.adapter.CustomAdapter;
import com.goodlearning.gloriamobile.adapter.CustomAdapter.IListItemController;
import com.goodlearning.gloriamobile.commons.Utils;
import com.goodlearning.gloriamobile.dto.GetAttendEndListDto;
import com.goodlearning.gloriamobile.dto.GetAttendListDto;
import com.goodlearning.gloriamobile.dto.GetAttendSuccessionDetail;
import com.goodlearning.gloriamobile.dto.GetAttendTotalDayDto;
import com.goodlearning.gloriamobile.dto.GetSuccessionCallResultDto;
import com.goodlearning.gloriamobile.net.JsonRequestThread.INetSuccessCallback;
import com.goodlearning.gloriamobile.net.JsonServiceRequester;
import com.goodlearning.gloriamobile.net.JsonWrapper;

/**
 * 기관실습 >> 기관 구술로 명칭 변경
 * @author rapty54
 *
 */
public class AdministrationAgencyPractice extends BaseActivity {
	
	GetAttendEndListDto noticeDto;
	
	GetAttendListDto attendListDto;
	
	GetSuccessionCallResultDto getSuccessionCallResultDto;
	
	GetAttendSuccessionDetail attendSuccessionDetail;
	
	GetAttendTotalDayDto attendTotalDayDto;
	
	ArrayList<GetSuccessionCallResultDto> callResultDtos;
	
	ArrayList<GetAttendSuccessionDetail> attendSuccessionDetails;
	
	CustomAdapter <GetAttendSuccessionDetail> customAdapter;
	
	ListView attendViewResultListView;
	
	TextView showYearGradeTerm,showGradeScore,showResponsibleProfessor,showClassOfDuration,showResidence,showAttendanceStatus;
	
	String classOfDayTotal,LbIdx,LIdx,attendLbix,attendLidx,resultLbidx,resultLidx,Lweek,tDate,gyosi;
	
	int countLate,countAttendance,countAbsence,countLeaveEarly=0;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.administration_agency_practice_layout);
		init();
	}
	/**
	 * getParcelableExtra >>  동등한 자료를 받기 위해서 하나의 Class 로 객체를 공유한다.
	 * Intent Key 는  1.getAttendEndListDto 2. getAttendListDto >> 두가지 형태
	 */
	public void init(){
		baseTitleLeftBtn.setVisibility(View.VISIBLE);
		baseTitleLeftBtn.setTextColor(getResources().getColor(R.color.administration_fifth_text_change));
		baseTitleLeftBtn.setText(R.string.btn_char1_shift_1);
		baseTitleLeftBtn.setTextSize(20.0f);
		baseTitleTv.setText("기관구술");
		baseTitleRightBtn.setVisibility(View.INVISIBLE);
		
		showYearGradeTerm=(TextView)findViewById(R.id.administration_end_of_class_year_grade_term);
		showGradeScore=(TextView)findViewById(R.id.administration_end_of_class_Agency_grade_score);
		showResponsibleProfessor=(TextView)findViewById(R.id.administration_end_of_class_proffessor_name);
		showClassOfDuration=(TextView)findViewById(R.id.administration_end_of_class_term);
		showResidence=(TextView)findViewById(R.id.administration_end_of_class_term_week);
		showAttendanceStatus=(TextView)findViewById(R.id.adminstration_end_of_class_attendance_state);
		attendViewResultListView=(ListView)findViewById(R.id.administration_end_of_class_AttendView_result_ListView);
		
		noticeDto = getIntent().getParcelableExtra("getAttendEndListDto");
		
		attendListDto = getIntent().getParcelableExtra("getAttendListDto");
		
		Utils.log("Notice:"+"["+noticeDto+"]"+"Attend:"+"["+attendListDto+"]");
		
		if(noticeDto!=null){
			
			attendLbix=noticeDto.getLbIdx();
			attendLidx=noticeDto.getLIdx();
			resultLbidx=attendLbix;
			resultLidx=attendLidx;
			
			requestAttendView(resultLbidx,resultLidx);
		}else if(attendListDto!=null){
			
			attendLbix=attendListDto.getLbIdx();
			attendLidx=attendListDto.getLIdx();
			resultLbidx=attendLbix;
			resultLidx=attendLidx;
			
			requestAttendView(resultLbidx,resultLidx);
		}
	}
	
	/**
	 * 지금 여기서 총 3 번을 호출해야되는데 지지.
	 */
	public void requestAttendView(final String Lbidx,final String Lidx){
		
		Utils.log("ResultLbidx:"+"["+Lbidx+"]"+"ResultLidx:"+"["+Lidx+"]");
			
		 JsonServiceRequester.requestGetAttendViewInfo(AdministrationAgencyPractice.this
				,new String(Base64.encodeBase64(getUserId().getBytes()))
		        , Lbidx, Lidx, new INetSuccessCallback() {
							
					@Override
					public void sendCallback(JsonWrapper jsonWrapper) {
						
						JSONArray attendViewInfoArray=jsonWrapper.getRootArray();
						
						callResultDtos=new ArrayList<GetSuccessionCallResultDto>();
						
						  for(int i=0;i<attendViewInfoArray.size();i++){
							  
							  JSONObject jsonObj = (JSONObject)attendViewInfoArray.get(i);
							 
							  getSuccessionCallResultDto=new GetSuccessionCallResultDto();
							  getSuccessionCallResultDto.sethYear(Utils.convertObjToString( jsonObj.get("hYear")));///년도
							  getSuccessionCallResultDto.setHnNm(Utils.convertObjToString( jsonObj.get("hnNm"))); ///학년
							  getSuccessionCallResultDto.settNm(Utils.convertObjToString( jsonObj.get("tNm")));
							  getSuccessionCallResultDto.setLecNm(Utils.convertObjToString( jsonObj.get("lecNm")));
							  getSuccessionCallResultDto.setGaeGangDay(Utils.convertObjToString( jsonObj.get("gaeGangDay")));
							  getSuccessionCallResultDto.setJongGangDay(Utils.convertObjToString( jsonObj.get("jongGangDay")));
							  getSuccessionCallResultDto.setNm(Utils.convertObjToString( jsonObj.get("nm")));///교수명
							  getSuccessionCallResultDto.setHakJeom(Utils.convertObjToString( jsonObj.get("hakJeom")));
							  getSuccessionCallResultDto.setHakgi(Utils.convertObjToString(jsonObj.get("hakgi")));///학기
							}
						  
						  baseTitleTv.setText(getSuccessionCallResultDto.getLecNm());
						  showYearGradeTerm.setText(getSuccessionCallResultDto.gethYear()+"년도 "+getSuccessionCallResultDto.getHnNm()+"학년 "+getSuccessionCallResultDto.gettNm());
						  showGradeScore.setText(getSuccessionCallResultDto.getLecNm()+"("+getSuccessionCallResultDto.getHakJeom()+"학점"+")");
						  showResponsibleProfessor.setText("강사명 : "+getSuccessionCallResultDto.getNm());
						  showClassOfDuration.setText("교육기간 : "+getSuccessionCallResultDto.getGaeGangDay()+" ~ "+getSuccessionCallResultDto.getJongGangDay());
						  showResidence.setText("이수기간 : "+"7"+"주");
						  
						 JsonServiceRequester.requestGetAttendTotal(AdministrationAgencyPractice.this
								, Lbidx, new INetSuccessCallback() {
									
									@Override
									public void sendCallback(JsonWrapper jsonWrapper) {
										
										JSONArray attendTotalArray=jsonWrapper.getRootArray();

										
										for(int i=0;i<attendTotalArray.size();i++){
											JSONObject jsonObj = (JSONObject)attendTotalArray.get(i);
											attendTotalDayDto=new GetAttendTotalDayDto();
											Utils.log("Total_Attend:"+"["+Utils.convertObjToString( jsonObj.get("totAttend"))+"]");
											attendTotalDayDto.setTotAttend(Utils.convertObjToString( jsonObj.get("totAttend")));
										}
										
										classOfDayTotal=attendTotalDayDto.getTotAttend();
										Utils.log("DayOfTotal:"+"["+classOfDayTotal+"]");
										
					   JsonServiceRequester.requestGetAttendView(AdministrationAgencyPractice.this
							   , new String(Base64.encodeBase64(getUserId().getBytes()))
							   , Lbidx, new INetSuccessCallback() {
							
									private int countInitLate,countInitAttendance,countInitAbsence,countInitLeaveEarly;
									
									private int totalLate,totalAttendence,totalAbsence,totalLeave;

									@Override
									public void sendCallback(JsonWrapper jsonWrapper) {
										
								        JSONArray attendViewArray=jsonWrapper.getRootArray();
								        
								        attendSuccessionDetails=new ArrayList<GetAttendSuccessionDetail>();
								        
								        Utils.log("수업 총 일수:"+"["+attendViewArray.size()+"]");
								        
								        for(int i=0;i<attendViewArray.size();i++){
								        	
								        	  JSONObject jsonObj = (JSONObject)attendViewArray.get(i);
								        	  
								        	  Lweek=Utils.convertObjToString(jsonObj.get("Lweek"));
								        	  tDate=Utils.convertObjToString(jsonObj.get("tDate"));
								        	  gyosi=Utils.convertObjToString(jsonObj.get("gyosi"));
								        	  String attendStatus=Utils.convertObjToString(jsonObj.get("attendStatus"));
								        	  

								        	  attendSuccessionDetail =new GetAttendSuccessionDetail();
											  attendSuccessionDetail.setLweek(Lweek);////주차
											  attendSuccessionDetail.settDate(tDate);////날짜
											  attendSuccessionDetail.setGyosi(gyosi);////교시
											  attendSuccessionDetail.setAttendStatus(attendStatus);///출석상태
											  attendSuccessionDetails.add(attendSuccessionDetail);
											  
											  if(attendStatus.equals("2")||attendStatus.equals("12")){
												  Utils.log("===========지각=========");
												  countInitLate=countLate++;
												  totalLate=countInitLate+1;
												  
												  Utils.log("지각_횟수:"+"["+totalLate+"]");
												  
											  }else if(attendStatus.equals("0")||attendStatus.equals("4")||attendStatus.equals("10")){
												  countInitAttendance=countAttendance++;
												  totalAttendence=totalLate+countInitAttendance+1;
												  
												  Utils.log("출석_횟수:"+"["+totalAttendence+"]");
												  
											  }else if(attendStatus.equals("1")){
												  countInitAbsence=countAbsence++;
												  totalAbsence=countInitAbsence+1;
												  
												  Utils.log("결석_횟수:"+"["+totalAbsence+"]");
												  
											  }else if(attendStatus.equals("3")){
												  countInitLeaveEarly=countLeaveEarly++;
												  totalLeave=countInitLeaveEarly+1;
												  
												  Utils.log("조퇴_횟수:"+"["+totalLeave+"]");
											  }
										}
								        
								           Utils.log("Week:"+"["+Lweek+"]"+"Tdate:"+"["+tDate+"]"+"Gyosi:"+"["+gyosi+"]");
								           int calculateAllAttendance=totalAttendence+totalLeave;
								        	
								           showAttendanceStatus.setText("수업: "+classOfDayTotal+" |"+"출석: "+calculateAllAttendance+" |"+"결석: "+totalAbsence+" | 지각: "+totalLate+" |"+"조퇴: "+totalLeave);
								           customAdapter=new CustomAdapter<GetAttendSuccessionDetail>(AdministrationAgencyPractice.this,R.layout.administration_agency_practice_row 
								           ,attendSuccessionDetails, listItemController);
								           attendViewResultListView.setAdapter(customAdapter);
								           
								           if(!Lweek.equals(null)){
								        	   showResidence.setText("이수기간 : "+Lweek+"주");
								           }
								           
									}
									 
						});
				  }
			  });
			}
		});
	}
	
	/**
	 * Main controller
	 */
	IListItemController<GetAttendSuccessionDetail> listItemController=new IListItemController<GetAttendSuccessionDetail>() {

		@Override
		public View controlView(List<GetAttendSuccessionDetail> items,int position, View convertView, ViewGroup parent) {
			
			GetAttendSuccessionDetail successionCallResultDto=(GetAttendSuccessionDetail)items.get(position);
			
			((TextView)convertView.findViewById(R.id.administration_agency_week_of_day_TextView)).setText(successionCallResultDto.getLweek()+"주차  "
			+ successionCallResultDto.gettDate()+" "+ successionCallResultDto.getGyosi()+"교시");
			
			TextView view=((TextView)convertView.findViewById(R.id.administration_agency_Attendance_State_show_TextView));
				view.setTag(position);
				view.setTag(view.getId(), successionCallResultDto);
				
			if(successionCallResultDto.getAttendStatus().equals("0")
				||successionCallResultDto.getAttendStatus().equals("4")
				||successionCallResultDto.getAttendStatus().equals("10")){
				
				view.setText("출석");
				view.setTextColor(Color.rgb(000, 051, 255));
				
			}else if(successionCallResultDto.getAttendStatus().equals("1")){
				view.setText("결석");
				view.setTextColor(Color.rgb(204, 000, 000));
				
			}else if(successionCallResultDto.getAttendStatus().equals("2")
					||successionCallResultDto.getAttendStatus().equals("12")){
				view.setText("지각");
				view.setTextColor(Color.rgb(255, 102, 051));
			}else if(successionCallResultDto.getAttendStatus().equals("3")){
				view.setText("조퇴");
				view.setTextColor(Color.rgb(255, 051, 153));
			}
			
			return convertView;
		}
	};
	
	/**
	 * 서버에서 받아온 개강 날짜와 종강 날짜의 차이일수를 구해와 주를 계산한다.
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public static int dayOfWeek(String startDate,String endDate){
		
		if(startDate==null||endDate==null) return 0;
		
		int weekresult = 0;
		
		int getdiffDay=getDiffDay(startDate, endDate);
		
		Utils.log("날짜 차이 일수:"+"["+getdiffDay+"]");
		
		int week=getdiffDay/7;
		
		Utils.log("한주를 7 로 나눈값"+week);
		
		Utils.log("한주를 7 로 나눈 나머지 "+getdiffDay%7);
		
		if(getdiffDay%7!=0){
			weekresult=week+1;
			Utils.log("여긴 하나더 추가 하는 부분"+weekresult);
		}else{
			weekresult=week;
		}
		
		return weekresult;
	}
	/**
	 * 두 날짜 사이의 일차를 구해온다.
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public static int getDiffDay(String startDate,String endDate){
		
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		
		Date sDate = null;
		Date eDate = null;
		try {
			sDate=sdf.parse(startDate);
			eDate=sdf.parse(endDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		
		return (int)((eDate.getTime()-sDate.getTime())/1000/60/60/24); 
	}
	/**
	 * 문자열에서 숫자만 추출 함수
	 * @param text
	 */
	public String textByDigit(String text){
		if ( text == null ) return "";
		  
		  StringBuffer sb = new StringBuffer();
		  for(int i = 0; i < text.length(); i++){
		    if( Character.isDigit( text.charAt(i) ) ) {
		    sb.append( text.charAt(i) );
		    }
		  }
		  return sb.toString();
		}
	
}
